import { useAccess, Access, useParams } from '@umijs/max';
import { PageContainer } from '@ant-design/pro-components';
import { Card, Descriptions, Button, Tag, Space, Steps, Table, message } from 'antd';
import { useState, useEffect } from 'react';
import { history } from '@umijs/max';

// 模拟订单详情数据
const mockOrderDetail = {
  id: '1001',
  customerName: '张三',
  customerPhone: '13800138000',
  customerAddress: '北京市朝阳区某某街道1号',
  amount: 299.99,
  status: 'paid',
  createTime: '2023-06-01 10:30:00',
  payTime: '2023-06-01 10:35:00',
  paymentMethod: '支付宝',
  items: [
    {
      id: '1',
      name: '商品1',
      price: 99.99,
      quantity: 2,
      subtotal: 199.98,
    },
    {
      id: '2',
      name: '商品2',
      price: 100.01,
      quantity: 1,
      subtotal: 100.01,
    },
  ],
  logistics: {
    company: '顺丰快递',
    trackingNumber: 'SF1234567890',
  },
};

// 订单状态映射
const orderStatusMap = {
  pending: { text: '待付款', color: 'orange' },
  paid: { text: '已付款', color: 'green' },
  shipped: { text: '已发货', color: 'blue' },
  completed: { text: '已完成', color: 'green' },
  cancelled: { text: '已取消', color: 'red' },
};

// 订单状态步骤
const orderSteps = [
  { title: '提交订单', status: 'pending' },
  { title: '付款成功', status: 'paid' },
  { title: '商品发货', status: 'shipped' },
  { title: '交易完成', status: 'completed' },
];

const OrderDetail: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const [order, setOrder] = useState<any>(null);
  const [loading, setLoading] = useState<boolean>(true);
  const access = useAccess();

  useEffect(() => {
    // 模拟API请求获取订单详情
    setTimeout(() => {
      setOrder({
        ...mockOrderDetail,
        id,
      });
      setLoading(false);
    }, 500);
  }, [id]);

  // 返回列表页
  const handleBack = () => {
    history.push('/orders/list');
  };

  // 取消订单
  const handleCancel = () => {
    setOrder({
      ...order,
      status: 'cancelled',
    });
    message.success('订单已取消');
  };

  // 发货
  const handleShip = () => {
    setOrder({
      ...order,
      status: 'shipped',
    });
    message.success('订单已发货');
  };

  // 完成订单
  const handleComplete = () => {
    setOrder({
      ...order,
      status: 'completed',
    });
    message.success('订单已完成');
  };

  // 获取当前订单状态的步骤索引
  const getCurrentStep = (status: string) => {
    const stepMap = {
      pending: 0,
      paid: 1,
      shipped: 2,
      completed: 3,
      cancelled: -1,
    };
    return stepMap[status as keyof typeof stepMap] || 0;
  };

  const columns = [
    {
      title: '商品ID',
      dataIndex: 'id',
      key: 'id',
    },
    {
      title: '商品名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '单价',
      dataIndex: 'price',
      key: 'price',
      render: (price: number) => `¥${price.toFixed(2)}`,
    },
    {
      title: '数量',
      dataIndex: 'quantity',
      key: 'quantity',
    },
    {
      title: '小计',
      dataIndex: 'subtotal',
      key: 'subtotal',
      render: (subtotal: number) => `¥${subtotal.toFixed(2)}`,
    },
  ];

  if (loading) {
    return (
      <PageContainer title="订单详情" loading>
        <Card loading />
      </PageContainer>
    );
  }

  return (
    <PageContainer
      title="订单详情"
      onBack={handleBack}
      extra={
        <Access accessible={access.isSuperAdmin || access.canAccessOrders}>
          <Space>
            {order.status === 'pending' && (
              <Button danger onClick={handleCancel}>
                取消订单
              </Button>
            )}
            {order.status === 'paid' && (
              <Button type="primary" onClick={handleShip}>
                发货
              </Button>
            )}
            {order.status === 'shipped' && (
              <Button type="primary" onClick={handleComplete}>
                完成订单
              </Button>
            )}
          </Space>
        </Access>
      }
    >
      <Space direction="vertical" style={{ width: '100%' }} size="large">
        <Card>
          <Steps
            current={getCurrentStep(order.status)}
            status={order.status === 'cancelled' ? 'error' : 'process'}
            items={orderSteps}
          />
        </Card>

        <Card title="订单信息">
          <Descriptions bordered column={2}>
            <Descriptions.Item label="订单号">{order.id}</Descriptions.Item>
            <Descriptions.Item label="订单状态">
              <Tag color={orderStatusMap[order.status as keyof typeof orderStatusMap].color}>
                {orderStatusMap[order.status as keyof typeof orderStatusMap].text}
              </Tag>
            </Descriptions.Item>
            <Descriptions.Item label="创建时间">{order.createTime}</Descriptions.Item>
            <Descriptions.Item label="支付时间">{order.payTime}</Descriptions.Item>
            <Descriptions.Item label="支付方式">{order.paymentMethod}</Descriptions.Item>
            <Descriptions.Item label="订单金额">¥{order.amount.toFixed(2)}</Descriptions.Item>
          </Descriptions>
        </Card>

        <Card title="客户信息">
          <Descriptions bordered column={1}>
            <Descriptions.Item label="客户姓名">{order.customerName}</Descriptions.Item>
            <Descriptions.Item label="联系电话">{order.customerPhone}</Descriptions.Item>
            <Descriptions.Item label="收货地址">{order.customerAddress}</Descriptions.Item>
          </Descriptions>
        </Card>

        {order.status !== 'pending' && order.logistics && (
          <Card title="物流信息">
            <Descriptions bordered column={1}>
              <Descriptions.Item label="快递公司">{order.logistics.company}</Descriptions.Item>
              <Descriptions.Item label="运单号">{order.logistics.trackingNumber}</Descriptions.Item>
            </Descriptions>
          </Card>
        )}

        <Card title="商品信息">
          <Table
            columns={columns}
            dataSource={order.items}
            rowKey="id"
            pagination={false}
            summary={(pageData) => {
              const total = pageData.reduce((sum, item) => sum + item.subtotal, 0);
              return (
                <Table.Summary.Row>
                  <Table.Summary.Cell index={0} colSpan={4} align="right">
                    总计：
                  </Table.Summary.Cell>
                  <Table.Summary.Cell index={1}>¥{total.toFixed(2)}</Table.Summary.Cell>
                </Table.Summary.Row>
              );
            }}
          />
        </Card>
      </Space>
    </PageContainer>
  );
};

export default OrderDetail;